package helper

import (
	"fmt"
	"time"

	"github.com/astaxie/beego"
	"github.com/gomodule/redigo/redis"
	"github.com/jinzhu/gorm"
	_ "github.com/go-sql-driver/mysql"
)

var (
	db        *gorm.DB
	redisPool *redis.Pool
)

func init() {
	// Redis
	initRedis()

	// mysql
	initDBLink()
}

func GetRedis() redis.Conn {
	conn := redisPool.Get()
	return conn
}

func GetDB() *gorm.DB {
	return db
}

func initRedis() {
	redisPool = &redis.Pool{
		MaxIdle:     5,
		IdleTimeout: 240 * time.Second,
		Dial:        func() (redis.Conn, error) { return redis.Dial("tcp", ":6379") },
	}
}

func initDBLink() {
	username := beego.AppConfig.String("DBUser")
	password := beego.AppConfig.String("DBPassword")
	host := beego.AppConfig.String("DBHost")
	port := beego.AppConfig.String("DBPort")
	database := beego.AppConfig.String("DBDatabase")

	link := fmt.Sprintf("%v:%v@(%v:%v)/%v?charset=utf8&parseTime=True&loc=Local", username, password, host, port, database)

	var err error
	db, err = gorm.Open("mysql", link)
	if err != nil {
		fmt.Println(err)
		Logger(err.Error(), "error")
		panic("mysql connect error:" + err.Error() + ";link：" + link)
	}
	db.DB().SetMaxIdleConns(10)
	db.DB().SetMaxOpenConns(100)

	// db.Callback().Create().Remove("gorm:update_time_stamp")
	// db.Callback().Update().Remove("gorm:update_time_stamp")
}
